package cn.hexcloud.dga.ds.service.impl;

import cn.hexcloud.dga.common.util.SqlUtil;
import cn.hexcloud.dga.ds.bean.TDsTaskDefinition;
import cn.hexcloud.dga.ds.mapper.TDsTaskDefinitionMapper;
import cn.hexcloud.dga.ds.service.TDsTaskDefinitionService;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jiangdan7
 * @since 2023-09-01
 */
@Service
@DS("ds")
public class TDsTaskDefinitionServiceImpl extends ServiceImpl<TDsTaskDefinitionMapper, TDsTaskDefinition> implements TDsTaskDefinitionService {

    @Override
    public Map<String, TDsTaskDefinition> getTableDefinitionMapByDt(String dt, List<String> tableNameList) {
        QueryWrapper<TDsTaskDefinition> queryWrapper = new QueryWrapper<TDsTaskDefinition>().in("name", tableNameList)
                .exists("select 1 from t_ds_task_instance where t_ds_task_instance.task_code = t_ds_task_definition.code and DATE_FORMAT(start_time,'%Y-%m-%d') = '" + SqlUtil.filterUnsafeSql(dt) + "'");
        List<TDsTaskDefinition> list = list(queryWrapper);
        /* 对sql字段进行赋值 */
        HashMap<String, TDsTaskDefinition> taskDefinitionMap = new HashMap<>(list.size());
        list.forEach(a -> {
            String sql = extractSqlFromTaskDefinition(a);
            a.setSql(sql);
            taskDefinitionMap.put(a.getName(), a);
        });
        return taskDefinitionMap;
    }

    private String extractSqlFromTaskDefinition(TDsTaskDefinition tDsTaskDefinition) {
        /* {"resourceList":[],"localParams":[],"rawScript":"#!/bin/bash\n\nsql=\"\ninsert overwrite table gmall.ads_order_by_province\nselect * from gmall.ads_order_by_province\nunion\nselect\n    '${do_date}' dt,\n    1 recent_days,\n    province_id,\n    province_name,\n    area_code,\n    iso_code,\n    iso_3166_2,\n    order_count_1d,\n    order_total_amount_1d\nfrom gmall.dws_trade_province_order_1d\nwhere dt='${do_date}'\nunion\nselect\n    '${do_date}' dt,\n    recent_days,\n    province_id,\n    province_name,\n    area_code,\n    iso_code,\n    iso_3166_2,\n    case recent_days\n        when 7 then order_count_7d\n        when 30 then order_count_30d\n    end order_count,\n    case recent_days\n        when 7 then order_total_amount_7d\n        when 30 then order_total_amount_30d\n    end order_total_amount\nfrom gmall.dws_trade_province_order_nd lateral view explode(array(7,30)) tmp as recent_days\nwhere dt='${do_date}';\n\"\n\nhive -e \"$sql\"","dependence":{},"conditionResult":{"successNode":[],"failedNode":[]},"waitStartTimeout":{},"switchResult":{}} */
        String taskParams = tDsTaskDefinition.getTaskParams();
        String rawScript = JSON.parseObject(taskParams).getString("rawScript");
        int beginIndex = rawScript.indexOf("with");
        if (beginIndex < 0) {
            beginIndex = rawScript.indexOf("insert");
        }
        if (beginIndex < 0) {
            return "";
        }
        int endIndex = rawScript.indexOf(";", beginIndex);
        if (endIndex < 0) {
            endIndex = rawScript.indexOf("\"", beginIndex);
        }
        return rawScript.substring(beginIndex, endIndex);

    }
}
